import streamlit as st
from data_interface.getUsersFromLocal import validateUser
from data_interface.updateUser import save_user_to_csv


class User:
    def __init__(self):
        self.username = "Guest"
        self.password = None
        self.email = None
        self.role = None
        self.account = None
        self.valid = False

    def login(self, username, password):
        """验证用户登录信息并设置登录状态"""
        print(f"Attempting login for user: {username}")  # 调试信息
        is_valid, data = validateUser(username, password)
        if is_valid:
            print(f"Login valid, data: {data}")  # 调试信息
            self.username = data['username']
            self.role = data['role']
            self.email = data['email'] 
            self.account = data['account']
            self.valid = True
            st.success(f"Login successful! Welcome {self.username} ({self.role})")
            return True
        else:
            return False
            
    def isValid(self):
        """
        检查用户是否有效
        """
        return self.valid
    
    def getName(self):
        """
        获取用户名
        """
        if self.valid:
            return self.username
        else:
            st.error("User name not found.")
            return "Guest"
    
    def getRole(self):
        """
        获取用户角色
        """
        if self.valid:
            return self.role
        else:
            st.error("User is not valid.")
            return None
    
    def getEmail(self):
        """
        获取用户邮箱
        """
        if self.valid:
            return self.email
        else:
            st.error("User is not valid.")
            return None

    def getAccount(self):
        """
        获取用户账户
        """
        if self.valid:
            return self.account
        else:
            st.error("User is not valid.")
            return None

    def logout(self):
        """
        登出用户
        """
        self.username = "Guest"
        self.password = None
        self.email = None
        self.role = None
        self.account = None
        self.valid = False
        st.success("Logout successful!")


def manage_login():
    """管理用户登录状态"""
    with st.form("login_form"):
        st.title("SportsHub - Login")
        username = st.text_input("Username:")
        password = st.text_input("Password:", type="password")
        submit_button = st.form_submit_button("Login")

        if submit_button:
            if st.session_state.user.login(username, password):
                return True
            else:
                st.error("Invalid username or password. Please try again.")
    return False

def submitForm(data):

    for k in data:
        print(f"{k}: {data[k]}")  # 打印每个字段的值

    if data["password"] == data["confirm_password"]:
        # 检查所有必填字段
        required_fields = {
            "username": data["username"],
            "password": data["password"],
            "name": data["name"],
            "birthday": data["birthday"],
            "gender": data["gender"],
            "email": data["email"],
            "phone": data["phone"],
            "account": data["account"]
        }
        
        print(f"字段值: {required_fields}")  # 调试信息
        
        if all(required_fields):
            print("所有字段已填写")  # 调print试信息
            user_data = {
                "username": data["username"],
                "password": data["password"],
                "name": data["name"],
                "role": "user",
                "birthday": data["birthday"].strftime("%Y-%m-%d"),  # 转换为字符串格式
                "gender": data["gender"],
                "email": data["email"],
                "phone": data["phone"],
                "account": data["account"]
            }
            print(f"准备保存用户数据: {user_data}")  # 调试信息
            try:
                save_user_to_csv(user_data)
                st.success("Register success")
                return True  # 返回 True 表示注册成功并登录了用户
            except Exception as e:
                print(f"Error during registration: {str(e)}")
                return False
        else:
            print("Please fill in all the information")
            return False
    else:
        return False

def register_user():
    """
    显示注册界面并处理注册逻辑
    """
    st.title("User Register")
    print("注册页面已加载")

    form_data = {
        "username": "",
        "password": "",
        "confirm_password": "",
        "name": "",
        "birthday": None,
        "gender": "",
        "email": "",
        "phone": "",
        "account": ""
    }
    # 使用更可靠的表单创建方式
    with st.form(key="register_form"):
        form_data["username"] = st.text_input("User name")
        form_data["password"] = st.text_input("Password", type="password")
        form_data["confirm_password"] = st.text_input("Confirm Password", type="password")
        form_data["name"] = st.text_input("Name", key="reg_name")
        form_data["birthday"] = st.date_input("Birthday", format="YYYY-MM-DD", min_value="1930-01-01")
        form_data["gender"] = st.selectbox("Gender", ["Male", "Female"])
        form_data["email"] = st.text_input("Email")
        form_data["phone"] = st.text_input("Phone")
        form_data["account"] = st.text_input("Payment Info")
        
        if st.form_submit_button("Submit"):
            print("提交按钮被点击")  # 调试信息
            for k in form_data:
                print(f"{k}: {form_data[k]}")  # 打印 # 调试信息
            return submitForm(form_data)
        # submitted = st.form_submit_button("Submit",on_click=lambda: submitForm(form_data))
    return False  # 返回提交按钮的状态